package com.shigui.news.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.shigui.news.dao.BaseDao;
import com.shigui.news.dao.NewsDao;
import com.shigui.news.model.Category;
import com.shigui.news.model.News;
/**
 * dao增删改查
 * curd
 * @author Shiguiwu
 *
 */
@Repository("newsDao")
public class NewsDaoImpl extends BaseDao implements NewsDao {
	
	@Autowired
	private SessionFactory sessionFactory;
	

	@Override
	public News selectById(Integer newsId) {

		Query query = getSession().createQuery("from News where newsId=:newsId");
		
		query.setInteger("newsId", newsId );
		
		return (News)query.uniqueResult();
	}

	@Override
	public List<News> select() {
		// TODO Auto-generated method stub
		return null;
	}
	@Transactional
	@Override
	public void insert(News news) {

		getSession().save(news);
	}
	@Transactional
	@Override
	public void update(News news) {

		getSession().update(news);
	}
	@Transactional
	@Override
	public void delete(News news) {


		getSession().delete(news);
	}

	@Override
	public List<News> getNewsList(Category category ,Integer page, Integer count) {
		/**
		 * page页数
		 * count每页的记录条数
		 * 
		 */
		Integer firstResultInteger = (page-1) * count;
		List<News> newsesList=null;
		
		newsesList = (List<News>) getSession().createCriteria(News.class)
				.add(Restrictions.eq("cateId", category.getCateId()))
				.setFirstResult(firstResultInteger)
				.setMaxResults(count)
				.addOrder(Order.desc("num"))
				.list();
		/**
		 * 返回列表
		 */
		
		
		return newsesList;
	}
	
	public List<News> getNewsList(Category category,Integer page){
		
		
		return this.getNewsList(category, page,10);
	}
	
	public List<News> getNewsList(Category category){
		
		return this.getNewsList(category, 1,10);
	}

	@Override
	public Integer countNewsList(Category category) {

		Criteria criteria = getSession().createCriteria(News.class)
				.add(Restrictions.eq("cateId", category.getCateId()))
				.setProjection(Projections.rowCount());
		
		Integer total = Integer.valueOf(criteria.uniqueResult().toString());
		
		return total;
	}
	@Transactional
	@Override
	public void updateNum(News news) {

		getSession().update(news);
		
	}

	

}
